<?php

/**
 * 获取当前控制器名
 *
 * @return string
 */
function getCurrentControllerName()
{
    return getCurrentAction()['controller'];
}

/**
 * 获取当前方法名
 *
 * @return string
 */
function getCurrentMethodName()
{
    return getCurrentAction()['method'];
}

/**
 * 获取当前控制器与方法
 *
 * @return array
 */
function getCurrentAction()
{
    $action = \Illuminate\Support\Facades\Route::current()->getActionName();
    list($class, $method) = explode('@', $action);

    return ['controller' => $class, 'method' => $method];
}


// 将目标转化为 collection 对象
if (!function_exists('collection')) {
    function collection($target)
    {
        // 如果目标已为 collection 对象,则直接返回
        if ($target instanceof \Illuminate\Support\Collection) {
            return $target;
        }
        // 否则将目标实例化为 collection 对象返回
        return collect($target);
    }
}

/**
 * 按符号截取字符串的指定部分
 * @param string $str 需要截取的字符串
 * @param string $sign 需要截取的符号
 * @param int $number 如是正数以0为起点从左向右截  负数则从右向左截
 * @return string 返回截取的内容
 */
function cutstr($str, $sign, $number)
{
    $array = explode($sign, $str);
    $length = count($array);
    if($number < 0) {
        $new_array = array_reverse($array);
        $abs_number = abs($number);
        if($abs_number > $length) {
            return 'error';
        }
        else {
            return $new_array[$abs_number - 1];
        }
    }
    else {
        if($number >= $length){
            return 'error';
        }
        else {
            return $array[$number];
        }
    }
}

function stamp($file)
{
    $path = public_path($file);
    return URL::asset($file).'?v='.md5(filemtime($path));
}


function formatMoney($value) 
{
  if($value == 0 || $value == '' || $value == null)
    return '';
  else
    return number_format($value,2);
}


function formatZero($value)
{
    if( $value == 0 || $value == '' || $value == null)
        return '';
    else
        return $value;
}

//生成随机颜色
function randRGB() 
{ 
  $str='0123456789ABCDEF'; 
    $estr='#'; 
    $len=strlen($str); 
    for($i=1;$i<=6;$i++) 
    { 
        $num=rand(0,$len-1);   
        $estr=$estr.$str[$num];  
    } 
    return $estr; 
}

function jsonEncode($status, $data = [], $message = '', $url = null)
{
    $status     = boolval($status);
    $data       = isset($data) ? $data : (object)array();
    $message    = strval($message);
    $code       = intval($status);
    //$url        = strval($url);

    $result = [
        'status'     => $status,
        'code' 		 => $code,
        'message'    => $message,
        'data'       => $data,
        'url'        => $url,
    ];

    return response()->json($result);
    
}

function jsonSuccess($data = [], $message='', $url = null)
{
    $message = $message ? $message : 'success';

    return $this->jsonEncode(true, $data, $message, $url);
}

function jsonFail($data = array(), $message='', $url = null)
{
    $message = $message ? $message : 'failed';

    return $this->jsonEncode(false, $data, $message, $url);
}


